// pages/releasePet/releasePet.js
import Toast from '@vant/weapp/toast/toast';
import {
  sendLostRequest
} from '../../api/pets'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    address: '',
    time: '',
    contact: '',
    detail: '',
    price: '',
    fileList: [],
    show: false,
    minDate: new Date(2010, 0, 1).getTime(),
    maxDate: new Date().getTime(),
  },

  // 日历
  onDisplay() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  formatDate(date) {
    date = new Date(date);

    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从 0 开始，所以需要加 1
    const day = date.getDate();


    // 返回格式化后的日期字符串
    return `${year}/${month}/${day}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      time: this.formatDate(event.detail),
    });
  },
  send() {
    const regex = /^1[3-9]\d{9}$/;
    if (this.data.name == '' ||
      this.data.address == '' ||
      this.data.time == '' ||
      this.data.contact == '' ||
      this.data.detail == '' ||
      this.data.price == '' ||
      this.data.fileList.length == 0) {
      Toast('请填写完整的信息');
      return
    } else if (!regex.test(this.data.contact)) {
      Toast('请输入正确的手机号');
      return
    } else {
      const o = {
        name: this.data.name,
        address: this.data.address,
        time: this.data.time,
        contact: this.data.contact,
        detail: this.data.detail,
        price: this.data.price,
        files: this.data.fileList.map(item => item.tempFilePath.slice(11))
      }
      sendLostRequest(res => {
        wx.showToast({
          title: '发布成功',
        })
        wx.redirectTo({
          url: `/pages/petsLost/petsLost`,
        })
      }, o)
    }
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    wx.uploadFile({
      url: 'http://localhost:3000/api/upload-cover', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        user: 'test'
      },
      success: (res) => {
        // 上传完成需要更新 fileList
        const {
          fileList = []
        } = this.data;
        fileList.push({
          ...file,
          url: res.data
        });
        this.setData({
          fileList
        });
      },
    });
  },
  previewImage(event) {
    const url = event.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前要显示的图片 url
      urls: [url] // 需要预览的图片 url 列表数组
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})